package com.itelite.service.impl;

import com.itelite.common.util.FileUtils;
import com.itelite.common.util.SecurityUtils;
import com.itelite.config.WebAppConfig;
import com.itelite.domain.pojo.Prize;
import com.itelite.domain.pojo.PrizeFile;
import com.itelite.mapper.GroupMapper;
import com.itelite.mapper.PrizeMapper;
import com.itelite.service.PrizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Objects;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/8/6-9:08
 **/
@Service
public class PrizeServiceImpl implements PrizeService {
    @Autowired
    private PrizeMapper prizeMapper;
    @Autowired
    private GroupMapper groupMapper;
    @Override
    public int uploadPrizeRecord(Prize prize) {
        prize.setUserId(SecurityUtils.getUserId());
        prizeMapper.insertPrize(prize);
        if(prize.getPrizeId()!=null){
            return prize.getPrizeId();
        }return -1;
    }

    @Override
    public boolean uploadPrizeFile(Integer prizeId,MultipartFile file) {
        String groupName = groupMapper.queryGroupNameByPrizeId(prizeId);
        File targetDir = FileUtils.createGroupDir(WebAppConfig.ROOT_DIR_PRIZE,groupName);
        //插入文件信息到数据库中
        String fileName = FileUtils.createFileName(Objects.requireNonNull(file.getOriginalFilename()));
        File desFile = new File(targetDir, fileName);
        try {
            file.transferTo(desFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PrizeFile fileInfo = new PrizeFile();
        String fileUrl =  File.separator+WebAppConfig.ROOT_DIR_PRIZE+File.separator+ groupName +File.separator+
                Calendar.getInstance().get(Calendar.YEAR)+File.separator+ desFile.getName();
        fileInfo.setFileUrl(fileUrl);
        fileInfo.setPrizeId(prizeId);
        fileInfo.setFileName(FileUtils.getFileName(file.getOriginalFilename()));
        fileInfo.setExtensionName(FileUtils.getExtensionName(file));
        return prizeMapper.insertPrizeFile(fileInfo)>0;
    }
}
